package com.kabuda.hot100.矩阵.medium;

import java.util.Arrays;
import java.util.List;

/**
 * @author kabuda
 * @Description
 * @create 2025-02-14 16:41
 * <p>
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 * <p>
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 * <p>
 * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 */
public class t54_螺旋矩阵 {
    public static void main(String[] args) {
        List<Integer> integers = spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
        System.out.println(integers);
    }



    /**
     * 右，下，左，上。
     *
     * @param matrix
     * @return
     */
    public static List<Integer> spiralOrder(int[][] matrix) {
        int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1, index = 0;
        Integer[] res = new Integer[(right + 1) * (bottom + 1)];
        while (true) {
            //左->右
            for (int i = left; i <= right; i++) {
                res[index++] = matrix[top][i];
            }

            //++为下个循环做准备，并且判断跳出循环
            if (++top > bottom) {
                break;
            }
            //上->下
            for (int i = top; i <= bottom; i++) {
                res[index++] = matrix[i][right];
            }


            if (--right < left) {
                break;
            }
            //右->左
            for (int i = right; i >= left; i--) {
                res[index++] = matrix[bottom][i];
            }


            if (--bottom < top) {
                break;
            }

            //下->上
            for (int i = bottom; i >= top; i--) {
                res[index++] = matrix[i][left];
            }


            if (++left > right) {
                break;
            }
        }

        return Arrays.asList(res);
    }


}
